package com.thinkit.bigdata.web.controller.sercutiry;

import com.thinkit.bigdata.web.model.config.SysArea;
import com.thinkit.bigdata.web.model.config.SysResource;
import com.thinkit.bigdata.web.model.config.SysResourceExample;
import com.thinkit.bigdata.web.model.result.ConfigResult;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.sec.JsTreeNode;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.service.config.ResourceService;
import com.thinkit.bigdata.web.service.sec.PermissionService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 权限配置：角色与资源关联关系维护
 * Created by lihongli on 2018/9/7
 */
@Controller
@RequestMapping("permission")
public class PermissionController {

    private static Logger logger = Logger.getLogger(PermissionController.class);

    @Resource
    private ResourceService resourceService;

    @Resource
    private PermissionService permissionService;

    /**
     * 查询出所有的资源信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/resourceAll")
    public List<SysResource> resourceAll(HttpServletRequest request) {
        logger.info("进入授权页面时加载所有的资源信息");
        SysResourceExample example = new SysResourceExample();
        example.setOrderByClause("type asc");
        return resourceService.selectByExample(example);
    }

    /**
     * 根据roleId获取对应的权限信息
     *
     * @param request
     * @param roleId
     * @return
     */
    @ResponseBody
    @RequestMapping("/permissionGet")
    public List<SysResource> permissionGet(HttpServletRequest request, Long roleId) {
        logger.info("获取角色id为" + roleId + "的权限信息");
        return permissionService.selectPermissions(roleId);
    }

    /**
     * 角色权限设置
     *
     * @param request
     * @param roleId
     * @param idList
     * @return
     */
    @ResponseBody
    @RequestMapping("/permissionSet")
    public ConfigResult permissionSet(HttpServletRequest request, @RequestParam("roleId") Long roleId, @RequestParam(value = "idList", required = false) List<Long> idList) {
        logger.info("给id为【" + roleId + "】的角色授权");
        try {
            int rowNum = permissionService.insertPermissions(roleId, idList);
            logger.info("角色【" + roleId + "】成功授权" + rowNum + "条权限信息");
            return new ConfigResult(Constants.SUCCESS, "授权操作成功");
        } catch (Exception e) {
            logger.error("【" + roleId + "】授权操作出现异常", e);
            return new ConfigResult(Constants.ERROR, "授权操作失败");
        }
    }

    /**
     * 显示资源树
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/showResourceTree")
    public JsTreeNode showResourceTree() {
        logger.info("【角色授权】获取资源树信息");
        JsTreeNode tree = new JsTreeNode();
        tree.setId(-1L);
        tree.setText("全选");
        permissionService.selectResources(tree);
        return tree;
    }

    /**
     * 首页菜单选项初始化数据获取
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/indexMenuInit")
    public List<SysResource> indexMenuInit(HttpServletRequest request) {
        List<SysResource> resourceList = new ArrayList<>();
        // 获取当前登录用户
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute(Constants.SESSION_USER_INFO);
        // 获取角色信息
        List<Long> roleIdList = user.getRoleidlist();
        if (roleIdList.isEmpty()) {
            // 如果角色信息为空 则需要判断下是否为未分配角色的普通用户（看不到菜单） 或者集团人员部门人员（可以看到所有菜单）
            SysArea sysArea = (SysArea) session.getAttribute("areaInfo");
            if (sysArea == null && 2 == (int) session.getAttribute("userIdentity")) {
                // 说明为超管 需要返回所有菜单信息
                SysResourceExample example = new SysResourceExample();
                example.setOrderByClause("orderNo asc");
                return resourceService.selectByExample(example);
            }
            // 返回空菜单
            return resourceList;
        }
        return permissionService.selectIndexMenu(roleIdList);
    }
}
